package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.constants.RedisConstant;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.po.PointsRecord;
import com.tianji.learning.domain.vo.PointsStatisticsVO;
import com.tianji.learning.enums.PointsRecordType;
import com.tianji.learning.mapper.PointsRecordMapper;
import com.tianji.learning.service.IPointsRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 学习积分记录，每个月底清零 服务实现类
 * </p>
 *
 * @author xjs
 */
@Service
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements IPointsRecordService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void addUserPoint(Long userId, Integer points, PointsRecordType type) {
        int realPoint = points;
        int maxPoints = type.getMaxPoints();
        if(maxPoints > 0){
            int totalPoints = queryTodayPointsByUserIdAndType(userId, type);
            if(totalPoints > maxPoints){
                log.warn("已经到达今日积分上限");
                return;
            }else{
                realPoint =  Math.min((maxPoints - totalPoints), points);
            }
        }
        PointsRecord record = new PointsRecord();
        record.setPoints(realPoint);
        record.setType(type.getValue());
        record.setUserId(userId);
        this.save(record);
        //排行榜 redis中的zset，key:月份 小key：userId
        String yyyyMM = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        String boardKey = RedisConstant.BOARD_PREFIX + yyyyMM;
        redisTemplate.opsForZSet().incrementScore(boardKey, ""+userId, realPoint);
    }

    @Override
    public List<PointsStatisticsVO> queryMyPointsToday() {
        Long userId = UserContext.getUser();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime start = DateUtils.getDayStartTime(now);
        LocalDateTime end = DateUtils.getDayEndTime(now);
        List<PointsStatisticsVO> voList = this.baseMapper.queryUserPointsByTimeGroupByType(userId, start, end);
        if(CollUtils.isEmpty(voList)){
            return voList;
        }
        voList.stream().forEach(vo->vo.setMaxPoints(PointsRecordType.of(Integer.valueOf(vo.getType())).getMaxPoints()));
        return voList;
    }

    private int queryTodayPointsByUserIdAndType(Long userId, PointsRecordType sign) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime start = DateUtils.getDayStartTime(now);
        LocalDateTime end = DateUtils.getDayEndTime(now);
        return this.baseMapper.queryPointsByUserIdTypeTime(userId, sign.getValue(), start, end);
    }
}
